/**
 * 小游戏管理
 */
class WeChatgGameManager {
	private _wx:any;
	private _sharedCanvas:any;
	//视频广告集合
	private video_ads = {};
	//当前视频广告id
    private current_video_ad_id = '';

	private _userInfoButton:any;
	private shareTime:number;
	private isInshare:boolean;
	private curShareId:number;
	
	public constructor() {
		this._wx = window['wx'];
		this._sharedCanvas = window["sharedCanvas"];
	}

	private static _instance:WeChatgGameManager;
	public static instance():WeChatgGameManager{
		if(!WeChatgGameManager._instance){
			WeChatgGameManager._instance = new WeChatgGameManager();
		}
		return WeChatgGameManager._instance;
	}

	public login(){
		return platform.login();
	}

	public init()
	{
		this.isInshare = false;
		this.shareTime = 0;
		this.onShow();
		this.onHide();
		this.onNetworkStatusChange();
		this.setKeepScreenOn();
		this.showShareMenu();
		RankManager.instance().loadFriendCloudStorage();
	}

	//分享
	private showShareMenu()
	{
		let wx = this._wx;
		if(wx)
		{
			return new Promise((resolve, reject) => {
				wx.showShareMenu();
			})
		}
	}

	//跳转
	public navigateToMiniProgram(appid?)
	{
		let wx = this._wx;
		if(wx)
		{
			return new Promise((resolve, reject) => {
				let data = {
					appId: appid,
					success(res) {
						// 打开成功
					},
					cancel(res) {
						
					}
				}
				wx.navigateToMiniProgram(data);
			})
		}
	}

	public getOpenDataContext()
	{
		let wx = this._wx;
		if(wx)
		{
			return wx.getOpenDataContext();
		}
	}

	//微信展示loading 
	public showLoading(title:string = '数据载入中'){
		let wx = this._wx;
		if(wx)
		{
			return new Promise((resolve, reject) => {
				wx.showLoading({
					title:title,
					mask:false,
					success:()=>{
					resolve();
					}
				});
			});
		}
	}

	/**
	 * 获取微信登录的一些数据（包含shareTicket的数据）
	 */
	public getOnShowData(){
		  //获取登录游戏的数据（包含shareTicket的数据）
		let wx = this._wx;
		if(wx)
		{
			return new Promise((resolve, reject) => {
				return resolve(wx.getLaunchOptionsSync());
			});
		}
  	}

	//微信隐藏loading
	public hideLoading(){
		let wx = this._wx;
		if(wx)
		{
			return new Promise((resolve, reject) => {
				wx.hideLoading({
					success:()=>{
						resolve();
					}
				});
			});
		}
	}

	/**
	 * 游戏进入前台
	 */
	private onShow(){
		let wx = this._wx;
		if(wx){
			wx.onShow((res) => {
				SoundManager.instance().goOn();
				if (res)
				{
					let equipment_no = res['query']['canshu'];
					let chuzhi_openid = res['query']['openid'];
					let dt = res['query']['dt'];
					let isGetPaper = RoleCache.instance().judgeIsAreadyGetPaper();
					if(void 0 !=  equipment_no && null != equipment_no && !isGetPaper && dt)
					{
						this.giftPaper(equipment_no, dt, chuzhi_openid);
					}
				}
				if(this.isInshare && !RoleCache.instance().reviewStatus)
				{
					this.isInshare = false;
					let time = egret.getTimer() - this.shareTime;
					if(time >= 2000)
					{
						GameUtil.dispatchEvent(EventConst.SHARE_SUCCESS, {type:this.curShareId});
					}
					else
					{
						egret.setTimeout(()=>{
							MessageUtil.tips('分享失败');
						},this, 500);
					}
					this.curShareId = null;
					this.shareTime = 0;
				}
			})
		}
	}

	/**
	 * 送纸巾活动
	 */
    public giftPaper(equipment_no, dt, chuzhi_openid)
	{
		let parma = {
			openid:chuzhi_openid,
			sbh:equipment_no,
			name:'xyx',
			pass:'xyx',
			dongzuo:'put',
			dt:dt
		}
		let url = 'https://api.xlqzh.com/xiaochengxu/chuzhi.aspx';
		let method = 'POST';
		let self = this;
		let Success_call = function(res)
		{
			self.hideLoading();
			RoleCache.instance().isAlreadySendPaper = true;
			if(res && res.data == 'ok')
			{	
				MessageUtil.tips('等待出纸哦~');
				self.sendALDEvent('giftPaperAc','fromAc' , 'giftPaper');
				let key_da = {
					key:'get_paper',
					value:true
				}
				// WeChatgGameManager.instance().setStorage(key_da, null);
			}
			else
			{
				MessageUtil.tips('出纸失败！');
			}
		}
		let Fail_call = function()
		{
			MessageUtil.tips('操作失败！');
			RoleCache.instance().isAlreadySendPaper = true;
			self.hideLoading();
		}
		
		let obj = {
			url:url,
			data:parma,
			method:method,
			header: {'content-type':'json'},
			success:Success_call,
			fail:Fail_call
		}
		self.showLoading('出纸中...');
		this.wxHttpRequest(obj);
	}

	public wxHttpRequest(obj)
	{
		let wx = this._wx;
		if(wx){
			LogUtil.log(obj);
			wx.request(obj)
		}
	}

	//阿拉丁自定义事件
	public sendALDEvent(eventName:string, key:string, value:string)
	{
		let wx = this._wx;
		if(wx)
		{
			wx.aldSendEvent(eventName,{key : value});
		}
	}

	/**
	 * 游戏进入后台
	 */
	private onHide(){
		let wx = this._wx;
		if(wx){
			wx.onHide((res) => {
				SoundManager.instance().stop();
				LoginPrase.instance().LogOut();
			})
		}
	}

	private _userInfo:any = {};
	public get userInfo(){
		return this._userInfo;
	}

	//设置屏幕常亮
	private setKeepScreenOn(){
		let wx = this._wx;
		if(!wx) return;
		return new Promise((resolve, reject) => {
			wx.setKeepScreenOn({
				keepScreenOn:true,
				success:()=>{
				resolve();
				}
			});
		});
	}

	/**
	 * 15ms震动
	 */
	public vibrateShort(){
		let wx = WeChatgGameManager.instance()._wx;
		if(wx){
			wx.vibrateShort();
		}
	}	

	public judgeIsIphoneX(){
		let wx = WeChatgGameManager.instance()._wx;
		if(wx){
			let res = wx.getSystemInfoSync();
			if(res)
			{
				let modelmes = res.model;
				if (modelmes.search('iPhone X') != -1 || modelmes.search('iPhone XS') != -1) {
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		return false;
	}

	public getUserInfo(call?:Function, scope?:any){
		// if(!this._userInfo){
			LogUtil.log('尝试拉取用户数据');
			platform.getUserInfo().then((e)=>{
				LogUtil.log('获得用户数据');
				this._userInfo = e;
				if(call){
					call.call(scope, e);
				}
			}).catch((e)=>{
				LogUtil.log('拉取用户数据失败');
				this.showUserInfoButton(call, scope);
			});
		// }
	}

	public showUserInfoButton(call?:Function, scope?:any){
		if(this._userInfoButton || !this._wx){
			return;
		}
		let data = this._wx.getSystemInfoSync();
		let windowWidth = data.windowWidth;
		let windowHeight = data.windowHeight;
		LogUtil.log('显示授权按钮')
		let scale = windowHeight / 1280;
		let w = 319*0.5;
		let h = 89*0.5;
		this._userInfoButton = this._wx.createUserInfoButton({
			type: 'image',
			// text: '获取用户信息'
			image:'resource/assets/weChat/userInfoButton.png',
			style: {
				left:windowWidth-w>>1,
				top: 870 * (scale < 1 ? scale: 1) ,
				width: w,
				height: h,
				borderRadius: 4
			}
		})
		this._userInfoButton.onTap((e) => {
			if(e.errMsg == 'getUserInfo:ok'){
				LogUtil.log('授权按钮成功回调');
				this._userInfo = e.userInfo;
				if(call){
					call.call(scope, e);
				}
			}
		})
	}

	public hideUserInfoButton(){
		if(this._userInfoButton){
			LogUtil.log('关闭授权按钮')
			this._userInfoButton.hide();
			this._userInfoButton.destroy();
			this._userInfoButton = null;
		}
	}

	/**
	 * 创建排行榜显示对象
	 */
	public createRankListDisplayObject(){
		let open = platform['openDataContext'];
		if(open){
			return open.createDisplayObject(null, GlobalManager.instance().curWidth(), GlobalManager.instance().curHeight());
		}
	}

	/**
	 * 向开放数据域发送数据
	 * @param data {ket:value}
	 */
	public sendMessageToOpen(data:any){
		let open = platform['openDataContext'];
		if(open){
			open.postMessage(data);
		}
	}

	/**
	 * 设置用户数据到微信后台，注意：不设置数据则无法通过getFriendCloudStorage获取用户数据
	 * @param data:json
	 */
	public setUserDataToCould(data:any[]){
		let open = platform['openDataContext'];
		if(open){
			open.setUserDataToCould(data);
		}
	}

	/**
	 * 播放视频广告
	 * param：
	 * 		ad_id:string 广告id
	 * 		Error_call:Function  发生错误或者观看失败的回调
	 * 		Success_call:Function 完整观看视频的回调函数
	 */
	public showVideoAd(ad_id:string, Success_call?:Function,Error_call?:Function, scope?)
	{	let wx = this._wx;
		if(wx)
		{
			let SDKVersion = wx.getSystemInfoSync().SDKVersion;
			// 无ad_id时弹出警告
			if (!(ad_id)) {
				wx.showModal({
					title: '系统提示', content: "请填入视频id", showCancel: false, cancelText: "", confirmText: "确定",
					success: () => {
						if(Error_call)
						Error_call.call(scope);
					}
				})
				return;
			}

			// 低版本兼容方法
			if (!(typeof(wx.createRewardedVideoAd) == 'function') || GameUtil.compareVersion(SDKVersion, GameConst.videoAd_version) == -1) {
				wx.showModal({
					title: '系统提示', content: "微信版本较低，暂不支持", showCancel: false, cancelText: "", confirmText: "确定",
					success: () => {
						if(Error_call)
						Error_call.call(scope);
						// MessageUtil.tips("观看视频失败");
					}
				})
				return;
			}

			this.video_ads[ad_id] = wx.createRewardedVideoAd({
				adUnitId: ad_id
			})
			this.current_video_ad_id = ad_id;
			// 播放广告时暂停背景音乐
			SoundManager.instance().swBGM();

			//加载广告视频
			this.video_ads[ad_id].load()
            .then(() => {
                // 加载成功后播放视频
                this.video_ads[ad_id].show();
            })
            // 加载失败时直接当作玩家视频广告观看成功
            .catch(err => {
				wx.showModal({
                    title: '系统提示', content: "暂时无法获取广告", showCancel: false, cancelText: "", confirmText: "确定",
                    success: () => {
                        if(Success_call)
						{
							Success_call.call(scope);
							this.current_video_ad_id = '';
						}
                    }
                })
            });

			this.video_ads[ad_id].onError(err => {
				console.log(err);
			});

			// 兼容新老版本广告关闭按钮
			this.video_ads[ad_id].onClose(res=> {
				if (res && res.isEnded || res === undefined) {
					// 用户完整观看广告
					LogUtil.log("回调成功");
					if(Success_call)
					{
						Success_call.call(scope);
						this.current_video_ad_id = '';
					}
				} else {
					// 用户提前点击了【关闭广告】按钮,进入失败回调
					LogUtil.log("回调失败");
					if(Error_call)
						Error_call.call(scope);
					this.current_video_ad_id = '';
					// MessageUtil.tips("观看视频失败");
				}
				// 关闭后重开背景音乐
				SoundManager.instance().swBGM();
				// 停止监听close方法
				this.video_ads[ad_id].offClose(res);
			})
		}
	}

	/**
	 * 插入banner广告
	 */
	 public showBannerAd(ad_id: string): any {
		let wx = this._wx;
		if(wx)
		{
			let SDKVersion = wx.getSystemInfoSync().SDKVersion;
			// 无ad_id时弹出警告
			if (!(ad_id)) {
				wx.showModal({
					title: '系统提示', content: "请填入广告id", showCancel: false, cancelText: "", confirmText: "确定",
					success: () => {}
				})
				return null;
			}
			// 低版本兼容方法
			let bannerAd = (GameUtil.compareVersion(SDKVersion, GameConst.videoAd_version) != -1 || typeof(wx.createRewardedVideoAd) == 'function') ? wx.createBannerAd({
				adUnitId: ad_id,
				style: {
					left: 0,
					top: 0,
					width: 350
				}
			}) : null;
			if (bannerAd) {
				bannerAd.onError(err => {
					console.log(err);
				});
				// bannerAd.show();
				let { screenWidth, screenHeight } = wx.getSystemInfoSync()
				bannerAd.onResize(res => {
					// banner广告放在底部
					bannerAd.style.top = screenHeight - bannerAd.style.realHeight;
				});
				bannerAd.style.width = screenWidth;
			}
			return bannerAd;
		}
    }

	/**
	 * 游戏网络处理
	 */
	public onNetworkStatusChange(){
		let wx = this._wx;
		if(wx){
			wx.onNetworkStatusChange((res) => {
				if(!res.isConnected)
				{
					//网络连接异常
				}
				else
				{
					//网络连接正常
				}
			})
		}
	}

	/**
	 * 设置分享数据
	 */
	public setShareData(data:Object){
		return platform.setShareData(data);
	}

	/**
	 * 分享
	 * 使用分享功能请调用 SharePrase.instance().requestOneAdvertisement({type:类型});
	 */
	public share(data?:any){
		let title = '我就看看';
		let imageUrl = "http://www.9665.com/uploadfile/2017/0717/20170717043846826.png";
		if(data)
		{
			//容错处理
			if(data["title"])
				title = data["title"];
			if(data["imgUrl"])
				imageUrl = data["imgUrl"]
		}
		let prama = data['prama'];
		let position;
		if(prama)
		{
			if(prama['position'] != null)
			position = prama['position'];
		}
		
		//分享必要参数
		let query = {
			fromUser:RoleCache.instance().openid,
			position:position
		}
		LogUtil.log(position);
		
		this.setShareData({
			title:title,
			imageUrl:imageUrl,
			query: StringUtil.jsonToHttpPostString(query),
			complete:()=>{
				
			},
			success:()=>{
				MessageUtil.tips("转发成功！");
				if(prama.type == ShareId.double)
				{	
					let call:Function = prama.call;
					if(call)
					{
						call.call(prama.scope);
					}
				}
			}
			// fail:(err)=>{
			// 	MessageUtil.tips("转发失败！");
			// }
		});
		platform.share();
		if(!RoleCache.instance().reviewStatus)
		{
			this.isInshare = true;
			this.shareTime = egret.getTimer();
			this.curShareId = prama.type;
		}
	}
	
}